package com.ctakit.sdk.app.widget.jsbridge;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Message;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.ctakit.sdk.app.R;
import com.ctakit.sdk.app.base.MyActivity;
import com.ctakit.sdk.app.service.ActionCallBack;
import com.ctakit.sdk.app.widget.fragmentmaster.app.FragmentContext;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by lizhenmin on 14/12/30.
 */

/**
 * 带进度条的WebView
 */
public class ProgressWebView extends WebView {

    private final String TAG = "webivew";
    protected ProgressBar progressbar;
    public static final int RESULT_CODE_ICE_CREAM = 102;
    public static final int REQUEST_CODE_LOLIPOP = 101;

    public ValueCallback<Uri[]> mFilePathCallback;
    public String mCameraPhotoPath;

    public ValueCallback<Uri> mUploadMessage;

    public static String keyNewWindow = "newWindow";
    protected boolean needNewWindow = true;
    protected Map<String, String> titleMap = new HashMap<>();

    protected ActionCallBack<String> actionTitleCallBack;
    protected OnWebLoadListener onWebLoadListener;

    protected Activity activity;

    private FileChooserListener fileChooserListener;
    protected OnWebLoadProgressChangedListener onWebLoadProgressChangedListener;

    public interface OnWebLoadListener {
        boolean onWebStartLoad(String decodeUrl, String url);
    }

    public void setOnWebLoadListener(OnWebLoadListener onWebLoadListener) {
        this.onWebLoadListener = onWebLoadListener;
    }

    public ProgressWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (context instanceof Activity) {
            this.activity = (Activity) context;
        }

        progressbar = new ProgressBar(context, null, android.R.attr.progressBarStyleHorizontal);
        progressbar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 3, 0, 0));
        progressbar.setProgressDrawable(context.getResources().getDrawable(R.drawable.webview_progress_color));
        addView(progressbar);
        setWebChromeClient(new WebChromeClient());
    }

    protected void openWindindow(String url, MyActivity activity) {

    }

    ;


    public class WebChromeClient extends android.webkit.WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                progressbar.setVisibility(GONE);
            } else {
                if (progressbar.getVisibility() == GONE)
                    progressbar.setVisibility(VISIBLE);
                progressbar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);

            if (onWebLoadProgressChangedListener != null){
                onWebLoadProgressChangedListener.OnWebLoadProgressChanged(view, newProgress);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (actionTitleCallBack != null) {
                titleMap.put(view.getUrl(), title);
                actionTitleCallBack.onSuccess(title);

            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
            new AlertDialog.Builder(getContext())
                    .setTitle("提示")
                    .setMessage(message)
                    .setPositiveButton(android.R.string.ok,
                            new AlertDialog.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    result.confirm();
                                }
                            })
                    .setCancelable(false)
                    .create()
                    .show();

            return true;
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            WebView newWebView = new WebView(view.getContext());
            newWebView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    if (overrideUrlLoading(view, url)) {
                        return true;
                    }


                    if (getContext() instanceof MyActivity) {
                        openWindindow(url, (MyActivity) getContext());
                    } else if (getContext() instanceof FragmentContext) {
                        Activity activity = (Activity) ((FragmentContext) getContext()).getBaseContext();
                        if (activity instanceof MyActivity) {
                            // ((MyActivity) activity).gotoActivity(Html5Activity.class,data);
                            openWindindow(url, (MyActivity) activity);
                        }
                    }

                    return true;
                }
            });
            WebViewTransport transport = (WebViewTransport) resultMsg.obj;
            transport.setWebView(newWebView);
            resultMsg.sendToTarget();
            return true;
        }

        //选择图片
// For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            if (activity != null) {
                activity.startActivityForResult(Intent.createChooser(i, "File Chooser"),
                        RESULT_CODE_ICE_CREAM);
            }


        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            if (activity != null) {
                activity.startActivityForResult(Intent.createChooser(i, "File Browser"),
                        RESULT_CODE_ICE_CREAM);
            }
        }

        //For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            boolean isIntercept = false;
            if (fileChooserListener != null){
                isIntercept = fileChooserListener.openFileChooser(uploadMsg,acceptType,capture);
            }

            if (!isIntercept){
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                if (activity != null) {
                    activity.startActivityForResult(Intent.createChooser(i, "File Chooser"),
                            RESULT_CODE_ICE_CREAM);
                }
            }
        }

        //For Android5.0+
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {
            boolean isIntercept = false;
            if (fileChooserListener != null){
                isIntercept = fileChooserListener.onShowFileChooser(webView,filePathCallback,fileChooserParams);
            }

            if (!isIntercept){

                //这句话建议屏蔽掉，当多次打开上传时会导致崩溃  但这是 google 官方做法
                if (mFilePathCallback != null) {
                    mFilePathCallback.onReceiveValue(null);
                }
                mFilePathCallback = filePathCallback;

                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
                    // Create the File where the photo should go
                    File photoFile = null;
                    try {
                        photoFile = createImageFile();
                        takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                    } catch (IOException ex) {
                        // Error occurred while creating the File
                        Log.e(TAG, "Unable to create Image File", ex);
                    }

                    // Continue only if the File was successfully created
                    if (photoFile != null) {
                        mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                Uri.fromFile(photoFile));
                    } else {
                        takePictureIntent = null;
                    }
                }

                Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
                contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
                contentSelectionIntent.setType("image/*");

                Intent[] intentArray;
                if (takePictureIntent != null) {
                    intentArray = new Intent[]{takePictureIntent};
                } else {
                    intentArray = new Intent[0];
                }

                Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
                chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
                chooserIntent.putExtra(Intent.EXTRA_TITLE, "选择方式");
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
                if (activity != null) {
                    activity.startActivityForResult(chooserIntent, REQUEST_CODE_LOLIPOP);
                }
            }

            return true;
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File imageFile = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        return imageFile;
    }

    protected boolean overrideUrlLoading(WebView view, String url) {
        return false;

    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        LayoutParams lp = (LayoutParams) progressbar.getLayoutParams();
        lp.x = l;
        lp.y = t;
        progressbar.setLayoutParams(lp);
        super.onScrollChanged(l, t, oldl, oldt);
    }


    public void setActionTitleCallBack(ActionCallBack<String> actionTitleCallBack) {
        this.actionTitleCallBack = actionTitleCallBack;
    }

    public void setNeedNewWindow(boolean needNewWindow) {
        this.needNewWindow = needNewWindow;
    }

    public void setFileChooserEventListener(FileChooserListener listener){
        fileChooserListener = listener;
    }

    public interface FileChooserListener{
        public boolean openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture);
        public boolean onShowFileChooser(
                WebView webView, ValueCallback<Uri[]> filePathCallback,
                android.webkit.WebChromeClient.FileChooserParams fileChooserParams);
    }

    public void setOnWebLoadProgressChangedListener(OnWebLoadProgressChangedListener onWebLoadProgressChangedListener) {
        this.onWebLoadProgressChangedListener = onWebLoadProgressChangedListener;
    }

    public interface OnWebLoadProgressChangedListener {
        void OnWebLoadProgressChanged(WebView view, int newProgress);
    }
}